﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CPOE.Framework.Caching
{
    public delegate void CachUpdateEventHandel(object obj);

    public static class ClientCacheManager
    {
        static Dictionary<Control, CachUpdateEventHandel> Actions = new Dictionary<Control, CachUpdateEventHandel>();
        /// <summary>
        /// 移除与控件相关的缓存function
        /// </summary>
        /// <param name="control"></param>
        public static void RemoveFromCache(this Control control)
        {

            foreach (Control ctl in control.Controls)
            {
                ctl.RemoveFromCache();
            }
            ClientCacheManager.Actions.Remove(control);
        }
        /// <summary>
        /// 扩展绑定数据依赖缓存更新而更新UI
        /// </summary>
        /// <param name="control"></param>
        /// <param name="action"></param>
        public static void BindDataFromCache(this Control control, CachUpdateEventHandel action)
        {
             
            if (ClientCacheManager.Actions.ContainsKey(control))
            {
                ClientCacheManager.Actions.Remove(control);
            }
            ClientCacheManager.Actions.Add(control, action);
            InvokeAction(action);
           
        }

        /// <summary>
        /// 重新调用数据刷新界面
        /// </summary>
        /// <param name="action">被缓存的action</param>
        static void InvokeAction(CachUpdateEventHandel action)
        {
            var obj = new Object[] { null };
            Application.OpenForms[0].BeginInvoke(action, obj);


        }

        /// <summary>
        /// 开启缓存更新监视器
        /// </summary>
        /// <param name="action">更新缓存的方法</param>
        /// <param name="timeOut">更新周期 秒为单位</param>
        public static void Start(Action action, int timeOut)
        {
            var task = new Task(() =>
            {
                while (true)
                {

                    action.Invoke();
                    if (Application.OpenForms.Count > 0)
                    {
                        foreach (var item in Actions)
                        {
                            InvokeAction(item.Value);
                        }
                    }

                    System.Threading.Thread.Sleep(1000 * timeOut);

                }

            });
            task.Start();
        }

    }


}
